import React, { Component } from 'react';
import {
  StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, PixelRatio
} from "react-native";
import { GLOBAL } from '../../../config/global';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { CommonDialog } from '../../../components/common/Dialog';
import WarningService from '../_common/service';
import { NewAccount } from '../../../components/common/newAccount';
import { SlideSelect } from '../../../components/common/slideSelect';

const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const tip2Img = require('../../../imgs/warning/tips2.png');
const tip1Img = require('../../../imgs/warning/tips1.png');
const TAB_LIST = [
  {
    name: '企业资质到期',
    id: 'qualification',
    count: 0,
  },
  {
    name: '授信账户到期',
    id: 'creditInfo',
    count: 0,
  }
];
export class EnterpriseWarning extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    let { tabIndex, headTitle } = navigation.state.params || {};
    return {
      headerTitle: headTitle || TAB_LIST[tabIndex].name,
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
      headerStyle: {  // 头部整体样式 
        elevation: 0,
        borderBottomWidth: 0,
        backgroundColor: style.color.themeColor
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  };

  constructor(props) {
    super(props)
    let { tabIndex, choice } = props.navigation.state.params || {};
    this.tabIndex = tabIndex || 0;
    this.state = {
      status: 'data',
      listData: [],
      refreshIcon: false, // 下拉刷新图标
      modalVisible: false,
      alertShow: false,
      options: [],
      choice: choice || {}
    }
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    this.totalPage = 1; // 总页数

    this.pageParams = { // TODO
      searchKey: '',
      pageNo: 1,
      pageSize: 10,
      warnType: TAB_LIST[tabIndex].id
    }
  }

  async componentWillMount() {
    await this.getSorage();
    await this.initPage();
    await this.getRecord();
  }

  //获取业务组织
  async getSorage() {
    const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
    const userInfo = JSON.parse(userInfoJson);
    this.setState({
      options: userInfo.corpInfoTOs || [],
      choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
    })
  }

  async initPage() {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    this.pageParams.warnType = TAB_LIST[this.tabIndex].id;
    this.pageParams.corpId = this.state.choice.corpId;
    let res = await WarningService.getWarnList(this.pageParams); // TODO
    if (res) {
      this.totalPage = res.totalPage;
      this.setState({
        status: res.rows.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
        refreshIcon: false
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }

  async getRecord() {
    let res1 = await WarningService.getWarnList({ warnType: 'qualification', corpId: this.state.choice.corpId }); // TODO
    let res2 = await WarningService.getWarnList({ warnType: 'creditInfo', corpId: this.state.choice.corpId }); // TODO
    this.setState({
      qualification: res1.recordCount || 0,
      creditInfo: res2.recordCount || 0
    })
  }


  // 刷新页面
  reloadPage=()=> {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this.getRecord();
    this.initPage();
  }

  // 下拉刷新
  refresh() {
    this.pageParams.pageNo = 1;
    this.reload = false;
    this.getRecord();
    this.initPage();
  }

  // 上拉翻页
  loadMore() {
    if (this.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this.initPage();
    }
  }

  changeTab(index) {
    if (this.tabIndex === index) return;
    this.tabIndex = index;
    this.pageParams.searchKey = '';
    this.props.navigation.setParams({
      headTitle: TAB_LIST[index].name
    })
    this.reloadPage();
  }

  // 搜索View
  _renderFilterWrap() {
    return (
      <View style={styles.filterWrap}>
        <View>
          <Image source={searchIcon} style={styles.searchIcon} />
          <TextInput
            ref="enterpriseInput"
            style={styles.searchInput}
            underlineColorAndroid='transparent'
            placeholder={"请输入企业名称"}
            placeholderTextColor="rgba(255, 255, 255, .8)"
            maxLength={30}
            returnKeyType={'search'}
            defaultValue={this.pageParams.searchKey}
            onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
            onSubmitEditing={() => { this.reloadPage(); }}
          />
        </View>
      </View>
    )
  }


  // 如何处理 View
  _renderToastWrap = () => {
    if (!this.tabIndex) { // TODO
      return (
        <View>
          <Text style={{ fontSize: 13 * scale, marginBottom: 4 * scale }}>统计维度：已到期、有效期少于30天</Text>
          <Text style={{ fontSize: 13 * scale }}>企业资质到期未处理时：</Text>
          <Text style={{ fontSize: 13 * scale, fontWeight: 'bold', marginTop: 20 * scale, marginBottom: 20 * scale }}>1.无法新增成交报告</Text>
          <Image style={{ width: 260 * scale, height: 200 * scale }} source={tip1Img} />
        </View>
      )
    } else if (this.tabIndex) {
      return (
        <View>
          <Text style={{ fontSize: 13 * scale, marginBottom: 4 * scale }}>统计维度：已到期、有效期少于30天</Text>
          <Text style={{ fontSize: 13 * scale }}>授信账户到期未处理时：</Text>
          <Text style={{ fontSize: 13 * scale, fontWeight: 'bold', marginTop: 20 * scale, marginBottom: 4 * scale }}>1.无法新增授信类型成交报告</Text>
          <Text style={{ fontSize: 13 * scale, fontWeight: 'bold', marginBottom: 20 * scale }}>2.销售授信订单未出库量将无法继续出库</Text>
          <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
            <Image style={{ width: 279 * scale, height: 170 * scale }} source={tip2Img} />
          </View>
        </View>
      )
    }
  }


  //tab View
  _renderTabWrap() {
    const { qualification, creditInfo } = this.state;
    return (
      <View style={styles.tabWrap}>
        {
          TAB_LIST.map((item, index) => {
            return (
              <TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(index) }} key={index} style={styles.tabItem}>
                <Text style={[styles.tabText, this.tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.name}</Text>
                <Text style={[styles.tabText, styles.tabCount, this.tabIndex == index ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.id == 'qualification' ? qualification : creditInfo}</Text>
              </TouchableOpacity>
            )
          })
        }
        <TouchableOpacity style={styles.tabTextWho} activeOpacity={1} onPress={() => { this.setState({ modalVisible: true }) }}>
          <Text style={styles.tabText}>如何处理？</Text>
        </TouchableOpacity>
      </View>
    )
  }

  _resultName = (nameList) => {
    let resultName = '';
    nameList && nameList.forEach((item, index) => {
      resultName += !index ? item : ',' + item;
    })
    return resultName;
  }

  //跳详情
  _details = (sendData) => {
    this.props.navigation.navigate('EnterpriseDetailsPage',
      {
        companyId: sendData.companyId,
        title: sendData.companyName,
        status: 'PASS',
        listType: '我的客户',
        initialPage: this.tabIndex ? 7 : 4, // 显示第几个tab
        choice: this.state.choice
      })
  }

  _renderListItem = (data) => {
    let itemData = data.item || {};
    let { companyName, companyId, itemList, organList } = itemData || {};
    return (
      <View style={styles.listItem}>
        <View style={{ paddingTop: 16 * scale, paddingBottom: 16 * scale, paddingLeft: 10 * scale, paddingRight: 10 * scale }}>
          <Text style={styles.enterpriseName} onPress={() => { this._details({ companyId, companyName }) }} >{`${companyName}>`}</Text>
          <Text style={{ fontSize: 10 * scale, paddingTop: 5 * scale, color: '#848A96' }}>(业务组织：{this.state.choice.corpName || '-'})</Text>
          {
            itemList && itemList.map((item, index) => {
              return (
                <View key={index} style={styles.warningItem}>
                  <Text style={{ fontSize: 13 * scale, fontWeight: 'bold' }}>{item.taskName}{this.tabIndex ? '| 授信账户' : ''} </Text>
                  {
                    item.overdue == '0' ?
                      <Text style={{ fontSize: 13 * scale, color: '#E02020' }}>{item.overdueDay || '-'}天后过期</Text> :
                      <Text style={{ fontSize: 13 * scale, color: '#E02020' }}>{item.overdueName}</Text>
                  }
                </View>
              )
            })
          }
        </View>
        <View style={styles.userInfo}>
          {
            organList && organList.map((item, index) => {
              return <Text key={index} style={styles.userName}>{`${item.bizTeamName} | ${this._resultName(item.staffNameList)}`}</Text>
            })
          }
        </View>
      </View>
    )
  }

  render() {
    let { status, listData, refreshIcon, modalVisible, alertShow, choice, options } = this.state;
    return (
      <View style={styles.container}>
        {options.length > 1 ? <NewAccount fn={(val) => { this.setState({ alertShow: val }) }} choice={choice.corpName || ''} /> : null}
        {this._renderFilterWrap()}
        {this._renderTabWrap()}
        {
          status == 'data' ? (<View style={{ flex: 1, paddingTop: 20 * scale, paddingBottom: 10 * scale }}>
            <FlatList
              data={listData}
              style={{ marginLeft: 12 * scale, marginRight: 12 * scale }}
              renderItem={this._renderListItem}
              refreshing={refreshIcon}
              onRefresh={() => { this.refresh() }}
              onEndReachedThreshold={0.1}
              onEndReached={() => { this.loadMore() }}
            />
          </View>) : null
        }
        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />) : null
        }
        <CommonDialog
          modalVisible={modalVisible}
          title={'提示'}
          onClosePress={() => { this.setState({ modalVisible: false }) }}
          renderCustom={this._renderToastWrap} />
        <SlideSelect alertShow={alertShow} options={options}
          select={(val) => {
            this.setState({ choice: val || options[0], alertShow: false }, () => {
              this.reloadPage();
            })
          }}
          unselect={() => {
            this.setState({ alertShow: false })
          }} />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: style.color.bgGray,
  },
  filterWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: style.color.themeColor,
    paddingTop: 14 * scale,
    paddingBottom: 14 * scale,
  },
  searchInput: {
    height: 36 * scale,
    width: 270 * scale,
    paddingLeft: 80 * scale,
    paddingRight: 12 * scale,
    backgroundColor: 'rgba(255, 255, 255, .18)',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 0,
    position: 'relative',
    borderRadius: 8 * scale,
    color: '#fff',
  },
  searchIcon: {
    width: 20 * scale,
    height: 22 * scale,
    position: 'absolute',
    left: 40 * scale,
    top: 8 * scale,
    zIndex: 9,
    opacity: 0.8,
  },
  tabWrap: {
    backgroundColor: style.color.themeColor,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    paddingLeft: 18 * scale,
    paddingRight: 18 * scale,
  },
  tabText: {
    color: '#fff',
    textAlign: 'center'
  },
  tabCount: {
    marginTop: 4 * scale
  },
  tabItem: {
    paddingTop: 14 * scale,
    paddingBottom: 12 * scale,
  },
  listItem: {
    backgroundColor: '#fff',
    borderRadius: 4 * scale,
    marginBottom: 22 * scale
  },
  enterpriseName: {
    fontSize: 13 * scale,
    color: style.color.themeColor,
  },
  userInfo: {
    paddingLeft: 10 * scale,
    paddingRight: 10 * scale,
    paddingBottom: 6 * scale,
    paddingTop: 8 * scale,
    borderStyle: 'solid',
    borderTopColor: '#E3E7F0',
    borderTopWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
  },
  warningItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: 13 * scale
  },
  userName: {
    fontSize: 12 * scale,
    marginBottom: 4 * scale,
    opacity: .8
  },
  tabTextWho: {
    paddingTop: 14 * scale
  }
})